export default {
  state: {
    products: [],
    productTypes: [],
    productCategories: {},
    q: '',
    c: '',
    sortKey: '',
    desc: false
  },

  mutations: {
    SET_PRODUCTS: (state, { products, params }) => {
      state.q = params.q
      state.c = params.c
      let pros = products.filter(product => {
        return !state.q || !state.q.length || product.name.indexOf(state.q) > -1
      }).filter(product => {
        return !state.c ||
          !state.c.length ||
          product.category.alias.toLowerCase() === state.c.toLowerCase()
      })

      if (state.sortKey) {
        pros.sort((p1, p2) => {
          return state.desc ? p2[state.sortKey] - p1[state.sortKey] :
            p1[state.sortKey] - p2[state.sortKey]
        })
      }

      state.products = pros
    },

    SET_PRODUCT_TYPES: (state, { productTypes }) => {
      state.productTypes = productTypes
    },

    SET_PRODUCT_CATEGORIES: (state, { productCategories }) => {
      state.productCategories = productCategories
    },

    SET_SORT: (state, { key, desc }) => {
      state.sortKey = key
      state.desc = desc
      state.products = state.products.sort((p1, p2) => {
        return state.desc ? p2[state.sortKey] - p1[state.sortKey] :
          p1[state.sortKey] - p2[state.sortKey]
      })
    }
  },

  actions: {
    FETCH_MALL_DATA: ({ dispatch }, { params }) => {
      return Promise.all([
        dispatch('FETCH_PRODUCTS', { params }),
        dispatch('FETCH_PRODUCT_TYPES'),
        dispatch('FETCH_PRODUCT_CATEGORIES')
      ])
    },

    FETCH_PRODUCTS: ({ dispatch, commit }, { params }) => {
      return dispatch('FETCH_ENDPOINT_DATA', { endpoint: 'products' })
        .then(({ products }) => { commit('SET_PRODUCTS', { products, params }) })
    },

    FETCH_PRODUCT_TYPES: ({ dispatch, commit }) => {
      return dispatch('FETCH_ENDPOINT_DATA', { endpoint: 'productTypes' })
        .then(({ productTypes }) => { commit('SET_PRODUCT_TYPES', { productTypes }) })
    },

    FETCH_PRODUCT_CATEGORIES: ({ dispatch, commit }) => {
      return dispatch('FETCH_ENDPOINT_DATA', { endpoint: 'productCategories' })
        .then(({ productCategories }) => { commit('SET_PRODUCT_CATEGORIES', { productCategories }) })
    }
  }
}